package com.gmall.order.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gmall.common.result.Result;
import com.gmall.model.activity.dto.SkuCoupon;
import com.gmall.model.cart.CartInfo;
import com.gmall.model.order.OrderFormDTO;
import com.gmall.model.order.OrderInfo;
import com.gmall.model.user.UserAddress;
import com.gmall.order.annotation.BeforeRepeat;
import com.gmall.order.annotation.Repeat;
import com.gmall.order.service.OrderService;
import com.gmall.order.service.WareHttpClient;
import com.gmall.user.feign.UserApiFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("api/order/")
public class OrderApiController {


    @Autowired
    UserApiFeignClient userApiFeignClient;

    @Autowired
    private OrderService orderService;


    @Autowired
    WareHttpClient wareHttpClient;
    /**
     *
     * @param cartInfoList
     * @return
     */
    @PostMapping("confirmOrder")
    @BeforeRepeat(value = "Order:RepeatUUID:")
    public Result<Map> confirmOrder(
            @RequestHeader Long userId,
            @RequestBody List<CartInfo> cartInfoList){

        //获取选择的购物车列表
        //获取用户的收货地址 3个地址进行选择
        //分拆订单，不做,skuid 26 27 28 仓库存储26，27（子订单）   28（另一个仓库）
        //计算订单的总金额
        BigDecimal totalAmount = new BigDecimal("0");
        for(int i=0;i<cartInfoList.size();i++){
            CartInfo cartInfo = cartInfoList.get(i);
            BigDecimal skuPrice = cartInfo.getSkuPrice();
            Integer skuNum = cartInfo.getSkuNum();
            SkuCoupon checkedCoupon = cartInfo.getCheckedCoupon();
            if(checkedCoupon!=null){
                BigDecimal payAmount = checkedCoupon.getPayAmount();
                totalAmount = totalAmount.add(payAmount);
            }else{//无优惠卷可以使用
                totalAmount = totalAmount.add(skuPrice.multiply(new BigDecimal(skuNum)));
            }
        }

        Map map = new HashMap<>();
        List<UserAddress> userAddressList = userApiFeignClient.findUserAddressList1(userId);
        if(userAddressList!=null && userAddressList.size()>0){
            map.put("userAddressList",userAddressList);
        }
        map.put("totalAmount",totalAmount);
        /*
        String tradeNo = orderService.genOrderNoUUID();
        //map.put("RepeatUUID",tradeNo);//不这样做，对代码的侵入太大，防重复提交
        response.addHeader("RepeatUUID",tradeNo);*/
        return Result.ok(map);
    }

    /**
     * 提交订单
     * @return
     */
    @PostMapping("submitOrder")
    @Repeat("Order:RepeatUUID:")
    public Result<String> submitOrder(
            @RequestHeader Long userId, @RequestBody OrderFormDTO orderFormDTO) throws IOException {
        /**
        String repeatuuid = request.getHeader("repeatuuid");
        if(orderService.hasOrderNoUUID(repeatuuid)){//第一次提交
            orderService.removeOrderNoUUID(repeatuuid);
        }else{
            throw new RuntimeException("订单已提交，请勿重复提交");
        }**/

        UserAddress userAddress = orderFormDTO.getUserAddress();
        List<CartInfo> cartList = orderFormDTO.getCartList();
        String comment = orderFormDTO.getComment();

        //检测库存
        cartList.forEach(cartInfo -> {
            Long skuId = cartInfo.getSkuId();
            Integer num = cartInfo.getSkuNum();
            try {
                boolean b = wareHttpClient.checkStock(skuId, num);
            } catch (IOException e) {
                throw new RuntimeException("SKUID=" + skuId+ " 库存检测失败");
            }
        });
        orderService.saveOrder(userId,userAddress,cartList,comment);

        return Result.ok();
    }

    @PostMapping("findOrderPage/{pageNo}/{pageSize}")
    public Result<Page<OrderInfo>> findOrderPage(
            @RequestHeader Long userId,
            @PathVariable Integer pageNo,
            @PathVariable Integer pageSize){

        Page<OrderInfo> orderInfoPage =
                orderService.findOrderPage(userId,pageNo,pageSize);
        return Result.ok(orderInfoPage);
    }

    /**
     * 根据订单Id 查询订单信息
     * api/order/getOrderInfo/{orderId}
     * @param orderId
     * @return
     */
    @GetMapping("/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable Long orderId) {

        return orderService.getOrderInfoById(orderId);
    }
}
